﻿<?php
include_once('dao_common.php');
include_once('dao_mcache.php');
define (CACHE_REFLESH,'cache_reflesh');
define (CACHE_LIVE_TIME,'cache_time');
global $max_cache_count ; //限制在内存中数组的size,如果每个数组元素很大，有可能还是有问题，但在我们的场景里可以忽略

$max_cache_count = 30*1000; //3万以内的

//通过输入的查询条件增加cachekey
//如$usefields='id:name',那么取$data[id].'_'.$data['name']，作为cachekey
function make_cache_key($name,&$data,$usefields)
{
	$usefields_array =explode(':',$usefields,10);
	foreach($usefields_array  as $key=>$value)
	{
		$name.=':'.$data[trim($value)];
	}
	return $name;
}

function dao_cached_query($key,&$dao,&$query_by,&$result,&$msg=null,$do_refresh=false,$live_time=120)
{
	if(strlen($live_time)&&is_numeric($live_time))
	{
		MCache::$live_time = $live_time;
	}
	if(!isset($do_refresh))
	{
		$do_refresh=false;
	}
	if($do_refresh==false)
	{
		$result = MCache::get($key);
		DAO_Log::debug(__FUNCTION__." by key: $key,result=".isset($result));
		if($result===false)
		{
			$result=array();
		}
		else
		{
			bo_session_set('cached','hit');
			return 0;
		}
	}
	$ret = $dao->query($query_by,$result,$msg);

	if($ret==0)
	{
		global $max_cache_count;
		if(sizeof($result)<$max_cache_count&&$live_time>1)
		{
			MCache::set($key,$result);
		}
	}
	return $ret;
}

function dao_cached_sql($key,&$dao,&$sql,&$result,&$msg=null,$do_refresh=false,$live_time=120)
{
	if(strlen($live_time)&&is_numeric($live_time))
	{
		MCache::$live_time = $live_time;
	}
	if(!isset($do_refresh))
	{
		$do_refresh=false;
	}
	if($do_refresh==false)
	{
		$result = MCache::get($key);
		DAO_Log::debug(__FUNCTION__." by key: $key,result=".isset($result));
		if($result===false)
		{
			echo "not hit\r\n";
			$result=array();
		}else
		{
			bo_session_set('cached','hit');
			return 0;
		}
	}
	$ret = $dao->run_sql($sql,$result,$msg);
	if($ret==0)
	{
		global $max_cache_count;
		if(sizeof($result)<$max_cache_count)
		{
			MCache::set($key,$result);
		}
	}
	return $ret;
}

if($argc>1)
{
	if($argv[1]=='ut_make_cache_key')
	{
		$data['f_service_id']=100;
		//$data['f_class_id']=1;
		$data['f_name'] = 'test';
		echo make_cache_key('test1',$data,'f_service_id' )."\r\n";
		echo make_cache_key('test1',$data,'f_class_id:f_service_id' )."\r\n";
		echo make_cache_key('test1',$data,'f_service_id:f_name')."\r\n";
	}

}
?>